/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hu.tothgya.timetable.elvira;

import hu.tothgya.timetable.Connection;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * This class create {@link Connection} objects from elvira urls.
 * @author tothgya
 */
public class ConnectionFactory {

    private String urlstr;
    private Calendar date;

    /**
     * Processes a connection list from an url.
     * @param url pointing to the journeys connections.
     */
    public ConnectionFactory(String url, Calendar date) {
        urlstr = url;
        this.date = date;
    }
    /**
     * Returns the connections for the journey.
     * @return the connections created from the url.
     */
    public List<Connection> getConnections() {

        List connections = new LinkedList<Connection>();


        Connection c = null;
        try {
            URL url = new URL(urlstr);
            InputStream stream = url.openStream();

            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document d = builder.parse(stream);
            NodeList nodelist = d.getElementsByTagName("a");

            for (int i = 0; i < nodelist.getLength(); i++) {
                Node n = nodelist.item(i);

                if(n.getAttributes().getNamedItem("href").getTextContent().indexOf("?v=") != -1)
                {
                    String s = n.getChildNodes().item(0).getNodeValue();
                    String departure = s.substring(1, s.indexOf(' '));
                    String start = s.substring(s.indexOf(' ') + 1);

                    n = n.getNextSibling();

                    s = n.getNodeValue();
                    String arrive = s.substring(1, s.indexOf(' '));
                    String destination = s.substring(s.indexOf(' ') + 1);

                    DateFormat df = new SimpleDateFormat("kk:mm");
                    Calendar departureTime = (Calendar) date.clone();
                    Calendar arriveTime = (Calendar) date.clone();
                    departureTime.setTime(df.parse(departure));
                    arriveTime.setTime(df.parse(arrive));
                    if(c != null && !c.destination.equals(start))
                    {
                        // Add local transportation placeholder if the next connection's
                        // start does not match with the previous destions
                        c= new Connection("Local", c.destination, null, start, null);
                        connections.add(c);
                    }
                    c = new Connection("Train", start, departureTime, destination, arriveTime);
                    connections.add(c);
                }
            }

        } catch (ParseException ex) {
            Logger.getLogger(ConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ioe) {
            Logger.getLogger(ConnectionFactory.class.getName()).log(Level.SEVERE, null, ioe);
        } catch (ParserConfigurationException pce) {
            Logger.getLogger(ConnectionFactory.class.getName()).log(Level.SEVERE, null, pce);
        } catch (SAXException se) {
            Logger.getLogger(ConnectionFactory.class.getName()).log(Level.SEVERE, null, se);
        }

        return connections;
    }
}
